package com.sure.minion.web.base;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.sure.minion.services.base.handler.DefaultDescription;
import com.sure.minion.services.base.handler.DescriptionGroup;
import com.sure.minion.services.base.handler.ResponseDefinitionFactory;
import com.sure.minion.services.base.handler.exception.DefaultAutoHandledException;

/**
 * 
 * @Description 异常拦截类，统一处理所有异常，并且翻译成json格式的异常信息展示给前端
 * @author mawei
 * @date 2015-2-6  下午7:40:17
 * Company: TravelSky
 */
@Component("exceptionResolver")
public class ExceptionHandler implements HandlerExceptionResolver {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {

		MappingJackson2JsonView view = new MappingJackson2JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();

		DefaultAutoHandledException defaultAutoHandledException = null;

		// 如果是自定义异常，则直接转换，否则作为统一的未知异常
		if (ex instanceof DefaultAutoHandledException) {
			defaultAutoHandledException = (DefaultAutoHandledException) ex;
		} else {
			defaultAutoHandledException = new DefaultAutoHandledException(DefaultDescription.UNKNOWN_EXCEPTION, ex);
		}

		// 获取异常所对应的错误码、错误提示信息以及log用信息
		DescriptionGroup descriptionGroup = ResponseDefinitionFactory.getDescriptionGroup(defaultAutoHandledException);
		
		logger.error(descriptionGroup.getMessageCode()+ "-" + descriptionGroup.getSystemLog(),ex);

		// 错误码和提示信息转化为json格式发到前端
		// 某些只有描述的异常，带上错误码
		attributes.put("messageCode", descriptionGroup.getMessageCode());
		attributes.put("messageDescription", descriptionGroup.getUserhint());
		attributes.put("responseError",defaultAutoHandledException.getResponseObject());
	
		view.setAttributesMap(attributes);

		ModelAndView mav = new ModelAndView();
		mav.setView(view);
		return mav;
	}

}